package com.ruoyi.iot.controller;

import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.iot.domain.IotRule;
import com.ruoyi.iot.service.IIotRuleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 联动规则Controller
 *
 * @author ruoyi
 * @date 2025-03-28
 */
@RestController
@RequestMapping("/iot/rule")
public class IotRuleController extends BaseController {
    @Autowired
    private IIotRuleService iotRuleService;

    /**
     * 查询联动规则列表
     */
    @GetMapping("/list")
    public TableDataInfo list(IotRule iotRule) {
        startPage();
        List<IotRule> list = iotRuleService.selectIotRuleList(iotRule);
        return getDataTable(list);
    }

    /**
     * 导出联动规则列表
     */
    @Log(title = "联动规则", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, IotRule iotRule) {
        List<IotRule> list = iotRuleService.selectIotRuleList(iotRule);
        ExcelUtil<IotRule> util = new ExcelUtil<IotRule>(IotRule.class);
        util.exportExcel(response, list, "联动规则数据");
    }

    /**
     * 获取联动规则详细信息
     */
    @GetMapping(value = "/{ruleId}")
    public AjaxResult getInfo(@PathVariable("ruleId") Long ruleId) {
        return success(iotRuleService.selectIotRuleByRuleId(ruleId));
    }

    /**
     * 新增联动规则（自动同步 eKuiper 创建流）
     */
    @Log(title = "联动规则", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody IotRule iotRule) {
        return toAjax(iotRuleService.createRuleAndStream(iotRule));
    }

    /**
     * 修改联动规则
     */
    @Log(title = "联动规则", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody IotRule iotRule) {
        return toAjax(iotRuleService.updateIotRule(iotRule));
    }

    /**
     * 删除联动规则（自动同步 eKuiper 删除流）
     */
    @Log(title = "联动规则", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ruleIds}")
    public AjaxResult remove(@PathVariable Long[] ruleIds) {
        return toAjax(iotRuleService.deleteRuleAndStream(ruleIds));
    }

    /**
     * 把规则同步到 EKuiper中
     *
     * @param ruleId 规则ID
     * @return R
     * @author Howe
     * @since 2025/6/9 15:14
     **/
    @Log(title = "联动规则", businessType = BusinessType.OTHER)
    @PostMapping("/syncRuleToEKuiper/{ruleId}")
    public AjaxResult syncRuleToEKuiper(@PathVariable Long ruleId) {
        return iotRuleService.syncRuleToEKuiper(ruleId);
    }
}
